package com.demo.inteceptor;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.demo.config.BufferedServletRequestWrapper;
import com.demo.utils.HttpUtil;
import com.demo.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.RequestWrapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RPInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ip = HttpUtil.getIpAddress(request);
//        Enumeration<String> headerNames = request.getHeaderNames();
        String requestURL = request.getRequestURL().toString().substring(22);
        String method = request.getMethod();
//        Map<String, Object> headerMap = new HashMap<>();
        Map<String, String> valueMap = new HashMap<>();
//        while (headerNames.hasMoreElements()) {
//            //获取名字
//            String name = headerNames.nextElement();
//            //把名字传到这里面,根据名称获取请求头的值  Authorization
//            if (null != name && (name.contains("authorization") ||name.contains("Authorization")) ) {
//                headerMap.put( name, request.getHeader(name));
//            }
//        }
        valueMap = WebUtils.getParameterMap(request);
        System.out.println("=========================================================" + "\n"
                + "请求时间/IP:" + sd.format(new Date()) + "  " + ip + "\n"
                + "请求地址:[" + method + "] " + requestURL + "\n"
//                + "----------请求头----------" + "\n"
//                + headerMap + "\n"
                + "---------请求参数----------" + "\n"
                + valueMap + "\n"
                + "=========================================================");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
